package com.google.code.jcooky.chat.client;

import java.awt.event.ActionEvent;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.URL;
import java.util.UUID;

import javax.swing.DefaultListModel;

import com.google.code.jcooky.chat.client.config.Configure;
import com.google.code.jcooky.chat.client.daemon.Receiver;
import com.google.code.jcooky.chat.client.daemon.Receiver.ReceiveListener;
import com.google.code.jcooky.chat.client.service.ChatService;

public class MainFrameEvent extends MainFrame implements ReceiveListener {
	
	private final ChatService service;
	
	private String id = UUID.randomUUID().toString();
	private Receiver receiver;
	
	public MainFrameEvent() throws IOException {
		String url = Configure.getInstance().getString("url");

		service = new ChatService(new URL(url));
		receiver = new Receiver(id, service, this);
		
		init();
	}
	
	private void init() {
		service.add(id);
		DefaultListModel model = (DefaultListModel)getConnectList().getModel();
		model.addElement(id);
		for(String eachId : service.getEnteredList(id)) model.addElement(eachId);
		
		new Thread(receiver).start();
	}

	@Override
	public void onAddText(String text) {
		getTextArea().setText(getTextArea().getText() + text);
	}

	@Override
	public void onEnterId(String id) {
		DefaultListModel model = (DefaultListModel)getConnectList().getModel();
		model.addElement(id);
	}

	@Override
	public void onCloseId(String id) {
		DefaultListModel model = (DefaultListModel)getConnectList().getModel();
		model.removeElement(id);
	}
	
	public void onWindowClosing(WindowEvent e) {
		receiver.close();
		service.remove(id);
	}

	public void onActiveSendBtn(ActionEvent e) {
		String text = getTextField().getText();
		service.addMessage(id, text);
		getTextField().setText("");
	}
}
